<template>
  <div class="pdf-container" ref="pdfContainerRef">
    <canvas
      v-for="pageIndex in pdfPages"
      :id="`pdf-canvas-${pageIndex}`"
      :key="pageIndex"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import * as PDFJS from "pdfjs-dist";

// 设置 worker 路径
PDFJS.GlobalWorkerOptions.workerSrc = 'pdf.worker.min.mjs'

const pdfContainerRef = ref<HTMLElement | null>(null);
const pdfPages = ref(0);
const pdfScale = ref(1.5);

// 加载 PDF 文件
const loadFile = async (url: string) => {
  const loadingTask = PDFJS.getDocument(url);
  loadingTask.promise
    .then(async (pdf) => {
      pdfPages.value = pdf.numPages; // 获取 PDF 总页数
      await nextTick(() => {
        renderPage(1, pdf); // 开始渲染第一页
      });
    })
    .catch((error) => {
      console.error("PDF 加载失败：", error);
    });
};

// 渲染 PDF 页面
const renderPage = (num: number, pdf: any) => {
  pdf.getPage(num).then((page: any) => {
    const canvas = document.getElementById(`pdf-canvas-${num}`) as HTMLCanvasElement;
    const ctx = canvas.getContext("2d")!;
    const viewport = page.getViewport({ scale: pdfScale.value });

    // 设置画布大小
    canvas.width = viewport.width;
    canvas.height = viewport.height;
    canvas.style.width = `${viewport.width}px`;
    canvas.style.height = `${viewport.height}px`;

    // 渲染页面
    const renderContext = {
      canvasContext: ctx,
      viewport: viewport,
    };
    page.render(renderContext);

    // 如果还有更多页面，递归渲染下一页
    if (num < pdfPages.value) {
      renderPage(num + 1, pdf);
    }
  });
};

// 在组件挂载时加载 PDF 文件
onMounted(() => {
  loadFile("01-中共中央 国务院关于建立国土空间规划体系并监督实施的若干意见(2019).pdf"); // 替换为你的 PDF 文件路径
});
</script>

<style scoped>
.pdf-container {
  height: 100%;
  overflow-y: scroll;
  overflow-x: hidden;
}
canvas {
  display: block;
  margin: 10px 0;
}
</style>